package com.fiberhome.nas.feature.main.viewmodel

import android.content.Context
import androidx.lifecycle.viewModelScope
import com.fiberhome.nas.core.common.base.viewmodel.BaseViewModel
import com.fiberhome.nas.core.data.repository.PhotoRepository
import com.fiberhome.nas.core.data.state.AppState
import com.fiberhome.nas.core.model.entity.PhotoInfo
import com.fiberhome.nas.core.network.di.NetworkManager
import com.fiberhome.nas.core.result.ResultHandler
import com.fiberhome.nas.core.result.asResult
import com.fiberhome.nas.feature.common.TIME_BUCKET_DAY
import com.fiberhome.nas.feature.main.model.SharedStateContainer
import com.fiberhome.nas.navigation.AppNavigator
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject


/**
 * [PhotoViewModel] 是一个继承自 [BaseViewModel] 的 ViewModel 类，
 * 用于管理与照片相关的业务逻辑和状态，借助 Hilt 进行依赖注入。
 */
@HiltViewModel
class PhotoViewModel @Inject constructor(
    appState: AppState,
    navigator: AppNavigator,
    @ApplicationContext private val context: Context,
    private val shareState: SharedStateContainer,
    private val photoRepository: PhotoRepository,
    private val networkManager: NetworkManager,
) : BaseViewModel(navigator, appState) {
    // 刷新状态
    private val _isRefreshing = MutableStateFlow(false)
    val isRefreshing: StateFlow<Boolean> = _isRefreshing.asStateFlow()

    private val _selectedItems = MutableStateFlow<Set<String>>(emptySet())
    val selectedItems: StateFlow<Set<String>> = _selectedItems.asStateFlow()

    private val _photos = MutableStateFlow<List<PhotoInfo>>(emptyList())
    val photos: StateFlow<List<PhotoInfo>> = _photos.asStateFlow()

    /**
     * 编辑模式状态
     */
    val editMode = shareState.switchEditMode.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = false
    )

    init {
        refreshData()
        // 监听 editMode 变化，当为 false 时清空选中项
        viewModelScope.launch {
            editMode.collect {
                if (!it) {
                    _selectedItems.update { emptySet() }
                }
            }
        }
    }

    /**
     * 刷新数据
     */
    fun refreshData() {
        _isRefreshing.value = true
        ResultHandler.handleResultWithData(
            scope = viewModelScope,
            flow = photoRepository.getPhotoList(TIME_BUCKET_DAY).asResult(),
            onData = { data ->
                _photos.value = data.items
                _isRefreshing.value = false
            }
        )
    }

    /**
     * 进入编辑模式
     */
    fun enterEditMode() {
        viewModelScope.launch { shareState.switchEditMode(true) }
    }


    /**
     * 切换全选状态
     *
     * @param select 全选状态
     */
    fun toggleSelectAll(select: Boolean) {
        _selectedItems.update {
            if (select) photos.value.map { it.id }.toSet() else emptySet()
        }
    }

    /**
     * 切换勾选状态
     *
     * @param id 照片id
     */
    fun toggleItemSelection(id: String) {
        _selectedItems.update {
            if (it.contains(id)) it - id else it + id
        }
    }

    /**
     * 切换勾选状态
     *
     * @param ids 照片id列表
     * @param select 勾选状态
     */
    fun toggleItemsSelection(ids: List<String>, select: Boolean) {
        _selectedItems.update {
            if (select) it + ids else it - ids.toSet()
        }
    }

    /**
     * 获取照片封面
     */
    fun getPhotoThumbUrl(id: String): String {
        return "${networkManager.baseUrl}/api/v1/tscss/assets/${id}/thumbnail"
    }

    /**
     * 获取照片原图
     */
    fun getPhotoOriginUrl(id: String): String {
        return "${networkManager.baseUrl}/api/v1/tscss/assets/${id}/original"
    }


}
